package top.ajunnihao.core.util.page;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;
import java.util.List;

/**
 * TODO 分页对象
 *
 * @author AJun
 * @version 1.0.0
 * @date 2020/5/9
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class PageInfo<T> implements Serializable {

    /* 前端提供 */
    /**
     * 当前页码
     */
    private int pageNum;

    /**
     * 每页数量
     */
    private int pageSize;

    /* 后端查询计算 */
    /**
     * 总记录数
     */
    private int total;

    /**
     * 总页数
     */
    private int pages;

    /**
     * 当前页的数据
     */
    private List<T> list;

    /**
     * 当前页的记录数量
     */
    private int size;

    /**
     * 前一页
     */
    private int prePage;

    /**
     * 下一页
     */
    private int nextPage;

    /**
     * 是否是首页
     */
    private boolean isFirstPage;

    /**
     * 是否是尾页
     */
    private boolean isLastPage;

    /**
     * 是否有前一页
     */
    private boolean hasPreviousPage;

    /**
     * 是否有下一页
     */
    private boolean hasNextPage;

    public PageInfo(int pageNum, int pageSize) {
        this.pageNum = pageNum;
        this.pageSize = pageSize;
    }

    public boolean getIsFirstPage() {
        return isFirstPage;
    }

    public void setIsFirstPage(boolean isFirstPage) {
        this.isFirstPage = isFirstPage;
    }

    public boolean getIsLastPage() {
        return isLastPage;
    }

    public void setIsLastPage(boolean isLastPage) {
        this.isLastPage = isLastPage;
    }

    /**
     * 获取分页开始索引(MySQL)
     */
    public int getPageStart() {
        return (pageNum - 1) * pageSize;
    }

    // 起始页码
    private int from;
    // 结束页码
    private int to;

    /**
     * 获取起始页码
     */
    public int getFrom() {
        from = pageNum - 2;
        to = pageNum + 2;
        if (from < 1) {
            from = 1;
            to = from + 4;
        }
        if (to > pages) {
            to = pages;
            from = to - 4;
        }
        if (pages < 5) {
            from = Math.max(from, 1);
            to = Math.max(pages, to);
        }
        return from;
    }

    /**
     * 获取结束页码
     */
    public int getTo() {
        return to;
    }

    /**
     * 分页
     */
    public void startPage() {
        pages = (total % this.pageSize == 0) ? (total / this.pageSize) : (total / this.pageSize + 1);
        size = list.size();
        prePage = this.pageNum - 1;
        nextPage = this.pageNum + 1;
        isFirstPage = (this.pageNum == 1);
        isLastPage = (this.pageNum == pages);
        hasPreviousPage = (this.pageNum > 1);
        hasNextPage = (this.pageNum < pages);
    }

}
